package com.itheima.reggie.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;

import static com.itheima.reggie.domain.Employee.STATUS_DISABLE;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //根据用户名查询,如果没查到,返回错误信息
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("用户名不存在");
        }
        //将前端传入的密码进行加密
        String passwordWithMd5 = SecureUtil.md5(password);//前端传入的加密之后的
        if (!StringUtils.equals(passwordWithMd5, employee.getPassword())) {
            return ResultInfo.error("密码错误");
        }
        //对当前用户进行状态检查
        if (employee.getStatus().equals(STATUS_DISABLE)){
            return ResultInfo.error("当前用户已被禁用");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) {
        employee.setPassword(SecureUtil.md5("123"));//设置123为默认密码
        employee.setStatus(Employee.STATUS_ENABLE);//状态

       /* // 后期需要优化
        employee.setCreateTime(new Date());
        employee.setUpdateTime(new Date());

        //临时写死,后期要从session中获取到当前操作用户
        employee.setCreateUser(1L);
        employee.setUpdateUser(1L);*/

       //自动填充参数,所以上面不用写了
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
       /* employee.setUpdateTime(new Date());
        employee.setUpdateUser(1L);*/
        employeeMapper.update(employee);
    }
}
